package cn.dapeng.thread.delayedQueue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @BelongProject study
 * @BelongPackage cn.dapeng.thread.delayedQueue
 * @Description 非同步的延时队列
 * @ClassName MyDelayQueueWithoutSyn
 * @Author xupenghong
 * @Date 2024/8/28 14:15
 * @Version 1.0.0
 */
public class MyDelayQueueWithoutSyn<E extends MyDelayed> extends MyAbstractQueue<E> {

    public MyDelayQueueWithoutSyn(int capacity) {
        super(capacity);
    }

    @Override
    public boolean add(E e) {
        final ReentrantLock lock = getLock();
        lock.lock();
        try {
            getArray().addToTail(e);
        } finally {
            lock.unlock();
        }
        return true;
    }

    @Override
    public E take() {
        final ReentrantLock lock = getLock();
        lock.lock();
        try {
            E first = peek();
            if (first == null) {
                return null;
            } else {
                for (; ; ) {
                    if (first.getDelay(TimeUnit.NANOSECONDS) <= 0) {
                        return getArray().removeFromTail();
                    }
                }
            }
        } finally {
            lock.unlock();
        }
    }

}
